package com.asm.shiroweb.config;

import com.asm.shiroweb.common.bean.UserBean;
import com.asm.shiroweb.service.UserService;
import com.asm.shiroweb.common.util.EncryptionPassword;
import com.asm.shiroweb.common.util.serializable.MyByteSourceSerializer;
import org.apache.shiro.authc.*;
import org.apache.shiro.realm.AuthenticatingRealm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

//@Configuration   // 好像不要这注解也行
public class MobileRealm  extends AuthenticatingRealm {

    @Autowired // 到底和 @Resource 什么区别
    private UserService userService;

    private Logger logger = LoggerFactory.getLogger(MyRealm.class);

    /*
    认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        logger.info("===========只有认证的  MobileRealm.doGetAuthenticationInfo ");


        UsernamePasswordToken userToken = (UsernamePasswordToken) token;

        // 根据 用户名 从数据库 获取用户
        final UserBean userBean = userService.queryUserByMobile(userToken.getUsername());

        if (null == userBean) {
            return  null;// 抛出：UnknownAccountException
        }
        // 【shiro 帮忙匹配密码】
        final SimpleAuthenticationInfo enticationInfo = new SimpleAuthenticationInfo(
                userBean,
                userBean.getUserPass(),
                new MyByteSourceSerializer(EncryptionPassword.SALT),
                this.getClass().getName());

        return enticationInfo;
    }
}
